package com.gcloud.mesh.dcs.chain.huawei;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.strategy.huawei.ListServersSolution;
import com.gcloud.mesh.header.exception.BaseException;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.huaweicloud.sdk.sms.v3.model.ListServersResponse;
import com.huaweicloud.sdk.sms.v3.model.SourceServersResponseBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component
@Slf4j
public class GetSourceServerId_1 extends AbstractHuaweiMigrationStep {
    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        HuaweiMigrationParam huaweiMigrationParam = JSONObject.toJavaObject(jsonObject,HuaweiMigrationParam.class);
        String sourceServerId = getSourceServerId(huaweiMigrationParam.getAccessKey(), huaweiMigrationParam.getSecretKey(), huaweiMigrationParam.getVmName());
        log.info("任务获取迁移的源资源id是"+sourceServerId);
        jsonObject.put("sourceServerId",sourceServerId);
        filterChain.doExec(schedulerJobId,jsonObject.toString(),filterChain,stepChain);
    }


    @Override
    public String chainName(String attach) {
        return "获取迁移源配置信息";
    }

    @Override
    public int getOrder() {
        return 1;
    }


    private String getSourceServerId(String ak, String sk, String name) {
        Map<String,String> sourceNameMap = mapNameAndSourceServer(ak, sk);
        String sourceServerId = sourceNameMap.get(name);
        if(sourceServerId == null) {
            throw new BaseException(String.format("该服务器%s可能未安装迁移agent，目前获取不到迁移源", name));
        }
        return sourceServerId;
    }

    private Map<String, String> mapNameAndSourceServer(String ak, String sk) {
        log.debug("映射华为云的迁移源和服务器对应关系");
        ListServersSolution listServersDetailsSolution = new ListServersSolution();
        Map<String, String> map = new HashMap<>();
        ListServersResponse res = listServersDetailsSolution.listServers(ak, sk);
        List<SourceServersResponseBody> sourceServers = res.getSourceServers();
        if(sourceServers != null) {
            for(SourceServersResponseBody body : sourceServers) {
                if(body.getCurrentTask() == null) {
                    map.put(body.getName(), body.getId());
                }
            }
        }
        log.debug("映射华为云的迁移源和服务器对应关系结束，对应关系如下"+map);
        return map;
    }
}
